package top.jacktgq.itheima.netty.protocol_design.optimization;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @Author CandyWall
 * @Date 2021/3/25--13:25
 * @Description
 */
@Slf4j
public class ClientConnTimeOut {
    public static void main(String[] args) throws IOException {
        // 服务器端通过 option()方法给ServerSocketChannel配置参数
        // 服务器端通过 childOption()方法给SocketChannel配置参数
        // 客户端通过 option()方法配置参数
        NioEventLoopGroup group = new NioEventLoopGroup();
        ChannelFuture channelFuture = new Bootstrap()
                .group(group)
                .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 5000)
                .channel(NioSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .connect("localhost", 8080);

        // 监听客户端连接事件
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    log.debug("客户端连接成功或者超时... {}", future.cause());
                } else {
                    log.debug("客户端连接成功");
                }
                // 监听客户端SocketChannel关闭事件，关闭客户端事件循环组中的事件循环
                Channel channel = channelFuture.channel();
                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        // 客户端关闭
                        log.debug("客户端正在关闭...");
                        group.shutdownGracefully();
                        log.debug("客户端关闭成功！");
                    }
                });
            }
        });
    }
}
